<?php


namespace App\Api\Repositories;


use App\Api\Bases\BaseController;
use App\Api\Models\Comments;
use App\Api\Services\SensitiveWords;
use App\Mongodb;
use Illuminate\Support\Facades\DB;

class CommentRepositorie
{
    //添加评论
    static public function addComment($comment)
    {
        $time = (new BaseController())->NowTime();
        $comment['add_time'] = $time;
        $comment['is_del'] = 0;
        $comment['is_reply'] = 0;
        $comment['is_show'] = 0;
        //敏感词过滤
        //$comment['again_content']=(new SensitiveWords())::filter($comment['again_content']);
        $words = self::say($comment['again_content']);
        if ($words) {
            if ($words['showapi_res_body']['remark'] == '检测成功') {
                //存在
                $content = '';
                foreach ($words['showapi_res_body']['labels'] as $item){
                    $content .= ' '.$item['words'][0];
                }
                $arrwords = explode(' ',$content);
                foreach ($arrwords as $item){
                    $comment['again_content'] = str_replace($item,'**',$comment['again_content']);
                }
                return  self::mongodb($comment);
                //return Comments::addComment($comment);
            } else {
                //不存在
                return  self::mongodb($comment);
            }
        } else {
            return false;
        }
    }

    public static function say($comment)
    {
        // 云市场分配的密钥Id
        $secretId = 'AKIDEh3heqBEhl5tt79c1C2gjY6RV87Ghg5Cb75i';
        // 云市场分配的密钥Key
        $secretKey = 'e806XmGsS3l6WiwZbxKulrc33w988V4aa1uiTwty';
        $source = 'market';

        // 签名
        $datetime = gmdate('D, d M Y H:i:s T');
        $signStr = sprintf("x-date: %s\nx-source: %s", $datetime, $source);
        $sign = base64_encode(hash_hmac('sha1', $signStr, $secretKey, true));
        $auth = sprintf('hmac id="%s", algorithm="hmac-sha1", headers="x-date x-source", signature="%s"', $secretId, $sign);

        // 请求方法
        $method = 'GET';
        // 请求头
        $headers = array(
            'X-Source' => $source,
            'X-Date' => $datetime,
            'Authorization' => $auth,
        );
        // 查询参数
        $queryParams = array(
            'content' => $comment,
        );
        // body参数（POST方法下）
        $bodyParams = array();
        // url参数拼接
        $url = 'https://service-owyxx71r-1255468759.ap-shanghai.apigateway.myqcloud.com/release/sensitiveWords';
        if (count($queryParams) > 0) {
            $url .= '?' . http_build_query($queryParams);
        }

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array_map(function ($v, $k) {
            return $k . ': ' . $v;
        }, array_values($headers), array_keys($headers)));
        if (in_array($method, array('POST', 'PUT', 'PATCH'), true)) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($bodyParams));
        }

        $data = curl_exec($ch);
        if (curl_errno($ch)) {
            curl_close($ch);
            return false;
        } else {
            curl_close($ch);
            return json_decode($data, true);

        }
    }

    public static function mongodb($comment)
    {
        $model = DB::connection('mongodb')->collection('cmc_comment');
        //链接mongodb的test集合
        $res = $model->insert($comment);//插入集合文档，数组形式传递参数
        return $res;
    }

    public static function getAllComment($goods_id)
    {
        $connection = Mongodb::connectionMongodb('cmc_comment');
        $result= $connection->get()->toArray();
        if($result){
            return $result;
        }else{
            return false;
        }
    }

}